package com.esri.core.tasks.tilecache;

import com.esri.core.ags.MapServiceInfo;
import com.esri.core.internal.tasks.TaskListener;
import com.esri.core.internal.tasks.ags.t;
import com.esri.core.internal.tasks.e;
import com.esri.core.internal.util.d;
import com.esri.core.io.EsriSecurityException;
import com.esri.core.io.UserCredentials;
import com.esri.core.map.CallbackListener;
import com.esri.core.map.ServerFile;
import com.esri.core.map.ServerFolder;
import com.esri.core.tasks.ags.geoprocessing.GPGetJobResultParameters;
import com.esri.core.tasks.ags.geoprocessing.GPGetJobResultTask;
import com.esri.core.tasks.ags.geoprocessing.GPJobResource;
import com.esri.core.tasks.ags.geoprocessing.GPMessage;
import com.esri.core.tasks.ags.geoprocessing.GPString;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;

/* loaded from: classes.dex */
public class ExportTileCacheTask {
    private static final String REQUEST_PARAMETERS_RECOVERY_FILENAME = "RequestParameters";
    private static final String TILE_CACHE_PATH_RECOVERY_FILENAME = "ExportTileCachePath";
    private static final String TILE_CACHE_STATUS_RECOVERY_FILENAME = "ExportTileCacheStatus";
    private UserCredentials _credentials;
    private String _recoveryDir;
    private String _serviceUrl;

    /* JADX INFO: Access modifiers changed from: private */
    /* loaded from: classes.dex */
    public final class TaskCallbackWrapper<T> implements TaskListener<T> {
        private boolean _errored;
        private final CallbackListener<T> _listener;

        private TaskCallbackWrapper(CallbackListener<T> callbackListener) {
            this._errored = false;
            this._listener = callbackListener;
        }

        @Override // com.esri.core.internal.tasks.TaskListener
        public void onError(Throwable th) {
            this._errored = true;
            CallbackListener<T> callbackListener = this._listener;
            if (callbackListener != null) {
                callbackListener.onError(th);
            }
        }

        @Override // com.esri.core.internal.tasks.TaskListener
        public void onCompletion(short s, T t) {
            CallbackListener<T> callbackListener = this._listener;
            if (callbackListener == null || s == 0 || this._errored) {
                return;
            }
            callbackListener.onCallback(t);
        }
    }

    public ExportTileCacheTask(String str, UserCredentials userCredentials) {
        this._serviceUrl = str;
        this._credentials = userCredentials;
    }

    public void setRecoveryDir(String str) {
        this._recoveryDir = str;
    }

    public MapServiceInfo fetchMapServiceInfo() throws Exception {
        return new t(this._serviceUrl, this._credentials).execute();
    }

    public Future<MapServiceInfo> fetchMapServiceInfo(final CallbackListener<MapServiceInfo> callbackListener) {
        return e.b.submit(new t(this._serviceUrl, this._credentials, new TaskListener<MapServiceInfo>() { // from class: com.esri.core.tasks.tilecache.ExportTileCacheTask.1
            @Override // com.esri.core.internal.tasks.TaskListener
            public void onError(Throwable th) {
                CallbackListener callbackListener2 = callbackListener;
                if (callbackListener2 != null) {
                    callbackListener2.onError(th);
                }
            }

            @Override // com.esri.core.internal.tasks.TaskListener
            public void onCompletion(short s, MapServiceInfo mapServiceInfo) {
                CallbackListener callbackListener2 = callbackListener;
                if (callbackListener2 != null) {
                    callbackListener2.onCallback(mapServiceInfo);
                }
            }
        }));
    }

    public Future<String> generateTileCache(ExportTileCacheParameters exportTileCacheParameters, CallbackListener<ExportTileCacheStatus> callbackListener, CallbackListener<String> callbackListener2, String str) {
        return generateTileCache(exportTileCacheParameters, callbackListener, callbackListener2, str, new File(this._recoveryDir, Integer.valueOf(exportTileCacheParameters.hashCode()).toString()));
    }

    private Future<String> generateTileCache(final ExportTileCacheParameters exportTileCacheParameters, final CallbackListener<ExportTileCacheStatus> callbackListener, final CallbackListener<String> callbackListener2, final String str, final File file) {
        return e.b.submit(new Callable<String>() { // from class: com.esri.core.tasks.tilecache.ExportTileCacheTask.2
            @Override // java.util.concurrent.Callable
            public String call() throws Exception {
                ExportTileCacheStatus requestTileCache;
                final File file2 = file;
                if (file2 == null) {
                    file2 = new File(ExportTileCacheTask.this._recoveryDir, Integer.valueOf(exportTileCacheParameters.hashCode()).toString());
                }
                File file3 = new File(file2, ExportTileCacheTask.TILE_CACHE_STATUS_RECOVERY_FILENAME);
                if (!file3.exists()) {
                    requestTileCache = ExportTileCacheTask.this.requestTileCache(exportTileCacheParameters, new CallbackListener<ExportTileCacheStatus>() { // from class: com.esri.core.tasks.tilecache.ExportTileCacheTask.2.1
                        @Override // com.esri.core.map.CallbackListener
                        public void onCallback(ExportTileCacheStatus exportTileCacheStatus) {
                            ExportTileCacheTask.this.generateRecoveryInfo(file2, exportTileCacheParameters, exportTileCacheStatus, str);
                        }

                        @Override // com.esri.core.map.CallbackListener
                        public void onError(Throwable th) {
                            if (callbackListener2 != null) {
                                callbackListener2.onError(th);
                            }
                        }
                    }, new ExportTileCacheStatusCallback() { // from class: com.esri.core.tasks.tilecache.ExportTileCacheTask.2.2
                        /* JADX WARN: Can't rename method to resolve collision */
                        @Override // com.esri.core.internal.tasks.PollingHelper.PollingStatusCallback
                        public void statusUpdated(TileCacheJobResource tileCacheJobResource) {
                            if (callbackListener != null) {
                                callbackListener.onCallback(new ExportTileCacheStatus(tileCacheJobResource, ExportTileCacheTask.this._serviceUrl));
                            }
                        }
                    }, new CallbackListener<ExportTileCacheStatus>() { // from class: com.esri.core.tasks.tilecache.ExportTileCacheTask.2.3
                        @Override // com.esri.core.map.CallbackListener
                        public void onCallback(ExportTileCacheStatus exportTileCacheStatus) {
                        }

                        @Override // com.esri.core.map.CallbackListener
                        public void onError(Throwable th) {
                            if (callbackListener2 != null) {
                                callbackListener2.onError(th);
                            }
                        }
                    });
                } else {
                    FileInputStream fileInputStream = new FileInputStream(file3);
                    requestTileCache = ExportTileCacheStatus.fromJson(d.a((InputStream) fileInputStream));
                    fileInputStream.close();
                }
                String downloadTileCacheInternal = ExportTileCacheTask.this.downloadTileCacheInternal(requestTileCache.getTileCacheJobResource(), str, ExportTileCacheTask.this.getTileCacheServerFolder(requestTileCache, new ExportTileCacheStatusCallback() { // from class: com.esri.core.tasks.tilecache.ExportTileCacheTask.2.4
                    /* JADX WARN: Can't rename method to resolve collision */
                    @Override // com.esri.core.internal.tasks.PollingHelper.PollingStatusCallback
                    public void statusUpdated(TileCacheJobResource tileCacheJobResource) {
                        if (callbackListener != null) {
                            callbackListener.onCallback(new ExportTileCacheStatus(tileCacheJobResource, ExportTileCacheTask.this._serviceUrl));
                        }
                    }
                }, new CallbackListener<ServerFolder>() { // from class: com.esri.core.tasks.tilecache.ExportTileCacheTask.2.5
                    @Override // com.esri.core.map.CallbackListener
                    public void onCallback(ServerFolder serverFolder) {
                    }

                    @Override // com.esri.core.map.CallbackListener
                    public void onError(Throwable th) {
                        if (callbackListener2 != null) {
                            callbackListener2.onError(th);
                        }
                    }
                }), callbackListener, callbackListener2);
                if (new File(downloadTileCacheInternal).exists()) {
                    ExportTileCacheTask.this.cleanupRecoveryInfo(file2);
                }
                CallbackListener callbackListener3 = callbackListener2;
                if (callbackListener3 != null) {
                    callbackListener3.onCallback(downloadTileCacheInternal);
                }
                return downloadTileCacheInternal;
            }
        });
    }

    public Future<Long> estimateTileCacheSize(final ExportTileCacheParameters exportTileCacheParameters, final CallbackListener<Long> callbackListener) {
        return e.b.submit(new Callable<Long>() { // from class: com.esri.core.tasks.tilecache.ExportTileCacheTask.3
            /* JADX WARN: Can't rename method to resolve collision */
            @Override // java.util.concurrent.Callable
            public Long call() throws Exception {
                Long l = new Long(-1L);
                ExportTileCacheStatus estimateTileCacheSize = ExportTileCacheTask.this.estimateTileCacheSize(exportTileCacheParameters);
                if (estimateTileCacheSize != null) {
                    if (estimateTileCacheSize.getStatus() == GPJobResource.JobStatus.SUCCEEDED) {
                        l = Long.valueOf(ExportTileCacheTask.this.getTileSizefromJson(((GPString) new GPGetJobResultTask(new GPGetJobResultParameters(estimateTileCacheSize.getJobResource(), "out_service_url", false), ExportTileCacheTask.this._serviceUrl + "/estimateExportTilesSize", ExportTileCacheTask.this._credentials).execute()).getValue()));
                    } else if (callbackListener != null) {
                        StringBuilder sb = new StringBuilder();
                        for (GPMessage gPMessage : estimateTileCacheSize.getJobResource().getMessages()) {
                            sb.append(gPMessage.getDescription());
                            sb.append("\n\r");
                        }
                        callbackListener.onError(new Throwable("Estimate tile cache size task failed: " + estimateTileCacheSize.getStatus() + "\r\n" + sb.toString()));
                    }
                    CallbackListener callbackListener2 = callbackListener;
                    if (callbackListener2 != null) {
                        callbackListener2.onCallback(l);
                    }
                }
                return l;
            }
        });
    }

    /* JADX WARN: Removed duplicated region for block: B:100:0x00bc A[EXC_TOP_SPLITTER, SYNTHETIC] */
    /* JADX WARN: Removed duplicated region for block: B:74:0x00b7  */
    /*
        Code decompiled incorrectly, please refer to instructions dump.
        To view partially-correct code enable 'Show inconsistent code' option in preferences
    */
    public void recoverAllJobs(com.esri.core.map.CallbackListener<com.esri.core.tasks.tilecache.ExportTileCacheStatus> r12, com.esri.core.map.CallbackListener<java.lang.String> r13) {
        /*
            Method dump skipped, instructions count: 219
            To view this dump change 'Code comments level' option to 'DEBUG'
        */
        throw new UnsupportedOperationException("Method not decompiled: com.esri.core.tasks.tilecache.ExportTileCacheTask.recoverAllJobs(com.esri.core.map.CallbackListener, com.esri.core.map.CallbackListener):void");
    }

    /* JADX INFO: Access modifiers changed from: private */
    public ExportTileCacheStatus requestTileCache(ExportTileCacheParameters exportTileCacheParameters, CallbackListener<ExportTileCacheStatus> callbackListener, ExportTileCacheStatusCallback exportTileCacheStatusCallback, CallbackListener<ExportTileCacheStatus> callbackListener2) {
        RequestAndPollTileCacheTask requestAndPollTileCacheTask = new RequestAndPollTileCacheTask(exportTileCacheParameters, this._serviceUrl, this._credentials, new TaskCallbackWrapper(callbackListener), new TaskCallbackWrapper(callbackListener2));
        requestAndPollTileCacheTask.setStatusCallback(exportTileCacheStatusCallback, callbackListener2);
        return requestAndPollTileCacheTask.call();
    }

    /* JADX INFO: Access modifiers changed from: private */
    public ExportTileCacheStatus estimateTileCacheSize(ExportTileCacheParameters exportTileCacheParameters) {
        RequestAndPollTileCacheTask requestAndPollTileCacheTask = new RequestAndPollTileCacheTask(exportTileCacheParameters, this._serviceUrl, this._credentials, null, null);
        requestAndPollTileCacheTask.setEstimateSize(true);
        return requestAndPollTileCacheTask.call();
    }

    /* JADX INFO: Access modifiers changed from: private */
    public ServerFolder getTileCacheServerFolder(ExportTileCacheStatus exportTileCacheStatus, ExportTileCacheStatusCallback exportTileCacheStatusCallback, final CallbackListener<ServerFolder> callbackListener) {
        PollAndFetchTileCacheTask pollAndFetchTileCacheTask = new PollAndFetchTileCacheTask(exportTileCacheStatus, this._credentials, new TaskListener<ServerFolder>() { // from class: com.esri.core.tasks.tilecache.ExportTileCacheTask.4
            private boolean _errored = false;

            @Override // com.esri.core.internal.tasks.TaskListener
            public void onError(Throwable th) {
                this._errored = true;
                CallbackListener callbackListener2 = callbackListener;
                if (callbackListener2 != null) {
                    callbackListener2.onError(th);
                }
            }

            @Override // com.esri.core.internal.tasks.TaskListener
            public void onCompletion(short s, ServerFolder serverFolder) {
                CallbackListener callbackListener2;
                if (this._errored || serverFolder == null || Thread.currentThread().isInterrupted() || (callbackListener2 = callbackListener) == null) {
                    return;
                }
                callbackListener2.onCallback(serverFolder);
            }
        });
        pollAndFetchTileCacheTask.setStatusCallback(exportTileCacheStatusCallback, callbackListener);
        return pollAndFetchTileCacheTask.call();
    }

    /* JADX INFO: Access modifiers changed from: private */
    public String downloadTileCacheInternal(final TileCacheJobResource tileCacheJobResource, String str, ServerFolder serverFolder, final CallbackListener<ExportTileCacheStatus> callbackListener, CallbackListener<String> callbackListener2) {
        boolean z;
        ServerFolder parent;
        if (serverFolder == null || Thread.currentThread().isInterrupted()) {
            return "";
        }
        File file = new File(str);
        if (file.exists()) {
            if (file.isDirectory()) {
                z = deleteDir(file);
            } else {
                z = file.delete();
            }
            if (!z && callbackListener2 != null) {
                callbackListener2.onError(new RuntimeException("File/Directory " + str + " already exists and could not be deleted."));
            }
        } else {
            z = true;
        }
        try {
            serverFolder.open(false);
        } catch (EsriSecurityException e) {
            if (callbackListener2 != null) {
                callbackListener2.onError(e);
            }
        } catch (Exception e2) {
            if (callbackListener2 != null) {
                callbackListener2.onError(e2);
            }
        }
        if (serverFolder.hasFiles()) {
            ServerFile serverFile = serverFolder.getFiles().get(0);
            if (callbackListener != null) {
                try {
                    serverFile.setProgressListener(new ServerFile.ProgressListener() { // from class: com.esri.core.tasks.tilecache.ExportTileCacheTask.5
                        @Override // com.esri.core.map.ServerFile.ProgressListener
                        public void reportProgress(String str2, long j, long j2) {
                            callbackListener.onCallback(new ExportTileCacheStatus(tileCacheJobResource, 1L, 1L, str2, j, j2));
                        }
                    });
                } catch (EsriSecurityException e3) {
                    if (callbackListener2 != null) {
                        callbackListener2.onError(e3);
                        return "";
                    }
                    return "";
                } catch (Exception e4) {
                    if (callbackListener2 != null) {
                        callbackListener2.onError(e4);
                        return "";
                    }
                    return "";
                }
            }
            return serverFile.download(new File(str), z).getAbsolutePath();
        }
        try {
            ServerFile findFile = serverFolder.findFile("conf.cdi");
            if (findFile == null || (parent = findFile.getParent()) == null) {
                return "";
            }
            if (callbackListener != null) {
                parent.setProgressListener(new ServerFolder.ProgressListener() { // from class: com.esri.core.tasks.tilecache.ExportTileCacheTask.6
                    @Override // com.esri.core.map.ServerFolder.ProgressListener
                    public void reportProgress(long j, long j2, String str2, long j3, long j4) {
                        callbackListener.onCallback(new ExportTileCacheStatus(tileCacheJobResource, j, j2, str2, j3, j4));
                    }
                });
            }
            parent.download(str);
            return parent.getPath();
        } catch (EsriSecurityException e5) {
            if (callbackListener2 != null) {
                callbackListener2.onError(e5);
                return "";
            }
            return "";
        } catch (Exception e6) {
            if (callbackListener2 != null) {
                callbackListener2.onError(e6);
                return "";
            }
            return "";
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void generateRecoveryInfo(File file, ExportTileCacheParameters exportTileCacheParameters, ExportTileCacheStatus exportTileCacheStatus, String str) {
        try {
            if (!file.exists()) {
                file.mkdirs();
            }
            writeRecoveryFile(file, exportTileCacheStatus.toJson(), TILE_CACHE_STATUS_RECOVERY_FILENAME);
            writeRecoveryFile(file, exportTileCacheParameters.toJson(), REQUEST_PARAMETERS_RECOVERY_FILENAME);
            writeRecoveryFile(file, str, TILE_CACHE_PATH_RECOVERY_FILENAME);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void writeRecoveryFile(File file, String str, String str2) {
        PrintStream printStream = null;
        try {
            try {
                PrintStream printStream2 = new PrintStream(new File(file, str2));
                try {
                    printStream2.print(str);
                    printStream2.close();
                } catch (FileNotFoundException e) {
                    e = e;
                    printStream = printStream2;
                    e.printStackTrace();
                    if (printStream != null) {
                        printStream.close();
                    }
                } catch (Throwable th) {
                    th = th;
                    printStream = printStream2;
                    if (printStream != null) {
                        printStream.close();
                    }
                    throw th;
                }
            } catch (FileNotFoundException e2) {
                e = e2;
            }
        } catch (Throwable th2) {
            th = th2;
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void cleanupRecoveryInfo(File file) {
        if (file == null || !file.exists() || Thread.currentThread().isInterrupted()) {
            return;
        }
        File[] listFiles = file.listFiles();
        if (listFiles != null) {
            for (File file2 : listFiles) {
                file2.delete();
            }
        }
        file.delete();
    }

    /* JADX INFO: Access modifiers changed from: private */
    public long getTileSizefromJson(String str) throws Exception {
        long j = -1;
        if (str != null && !str.isEmpty()) {
            JsonParser c = d.c(str);
            c.nextToken();
            if (c.getCurrentToken() != JsonToken.START_OBJECT) {
                return -1L;
            }
            while (c.nextToken() != JsonToken.END_OBJECT) {
                String currentName = c.getCurrentName();
                c.nextToken();
                if ("totalSize".equals(currentName)) {
                    j = c.getLongValue();
                } else {
                    c.skipChildren();
                }
            }
        }
        return j;
    }

    private boolean deleteDir(File file) {
        File[] listFiles;
        int i;
        boolean z = true;
        if (file.exists() && file.isDirectory() && (listFiles = file.listFiles()) != null) {
            int length = listFiles.length;
            while (i < length) {
                File file2 = listFiles[i];
                if (file2.isDirectory()) {
                    i = deleteDir(file2) ? i + 1 : 0;
                    z = false;
                } else {
                    if (file2.delete()) {
                    }
                    z = false;
                }
            }
            file.delete();
        }
        return z;
    }
}
